package com.zl.learning.json.gson;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import org.junit.Test;

import java.util.Arrays;

public class GsonTest1 {

    @Test
    public void test1() {
        Gson gson = new Gson();
        User u = new User(1, "zhangsan", "123456a");
        String a = gson.toJson(u);
        System.out.println(a);
    }

    @Test
    public void test2() {
        Gson gson = new GsonBuilder().registerTypeAdapter(User.class, new UserTypeAdapter()).create();
        User u = new User(1, "zhangsan", "123456a");
        String a = gson.toJson(u);
        System.out.println(a);
    }

    @Test
    public void test3() {
        String a = "{\"userPassword\":\"123456a\",\"userName\":\"zhangsan\",\"userId\":1}";
        Gson gson = new GsonBuilder().registerTypeAdapter(User.class, new UserTypeAdapter()).registerTypeAdapter(User.class, new UserJsonDeserializer()).create();
        User u = gson.fromJson(a, User.class);
        System.out.println(u);
    }

    @Test
    public void test4() {
//        String a = "{\"code\":1,\"data\":{\"userPassword\":\"2019-07-03 17:25:57.637\",\"userId\":1,\"userName\":\"zhansan\"},\"msg\":\"success\"}";
        String a = "{\"code\":0,\"msg\":\"success\",\"data\":{\"userPassword\":\"123456a\",\"ClassRoom\":{\"id\":2,\"name\":\"一班\"},\"userName\":\"zhangsan\",\"userId\":1}}";
        Gson gson = new GsonBuilder().registerTypeAdapter(User.class, new UserTypeAdapter()).registerTypeAdapter(User.class, new UserJsonDeserializer()).create();
        Result<User> u = gson.fromJson(a, new TypeToken<Result<User>>() {
        }.getType());

        System.out.println(u);
    }

    @Test
    public void test5() {
        Gson gson = new GsonBuilder().registerTypeAdapter(User.class, new UserTypeAdapter()).create();
        User<ClassRoom> u = new User<>(1, "zhangsan", "123456a", new ClassRoom(2, "一班"));
        Result<User> result = new Result<>(0, "success", u);
        String a = gson.toJson(result);
        System.out.println(a);
    }

    @Test
    public void test6() {
        PageData<ClassRoom> data = new PageData<ClassRoom>(100L, 2, 10, 20, Arrays.asList(new ClassRoom(1, "一班")));
        Gson gson = new GsonBuilder().registerTypeAdapter(PageData.class, new PageDataParser()).create();
        String val = gson.toJson(data);
        System.out.println(val);
    }
    @Test
    public void test7() {
        Gson gson = new GsonBuilder().registerTypeAdapter(PageData.class, new PageDataParser()).create();
        String val = "{\"total\":100,\"page_num\":2,\"page_size\":10,\"pages\":20,\"result\":[{\"id\":1,\"name\":\"一班\"}]}";
        PageData<ClassRoom> pageData  = gson.fromJson(val,PageData.class);
        System.out.println(pageData);
    }

}
